package com.ydcode.utils;

import java.sql.*;

import com.mysql.jdbc.Driver;

public class BaseDao {

	private final String URL = "jdbc:sqlserver://localhost:1433;databasename=company";

	private final String DNAME = "sa";

	private final String DPASS = "";

	public Connection getConn() throws ClassNotFoundException, SQLException {
		Connection conn = null;
		new Driver();
		// Class.forName(DRIVER);
		if (conn == null) {
			conn = DriverManager.getConnection(URL, DNAME, DPASS);
		}
		return conn;
	}

	public int executeSQL(String sql, String[] param) {
		int num = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;

		try {
			conn = this.getConn();
			pstmt = conn.prepareStatement(sql);
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					pstmt.setString(i + 1, param[i]);
				}
			}
			num = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.closeAll(conn, pstmt, null);
		}

		return num;
	}

	public void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
